package cn.wolfcode.wolf.user.service.impl;

import cn.wolfcode.wolf.core.exception.BusinessException;
import cn.wolfcode.wolf.redis.utils.RedisCache;
import cn.wolfcode.wolf.user.redis.key.UserRedisKeyPrefix;
import cn.wolfcode.wolf.user.service.SmsService;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SmsServiceImpl implements SmsService {
    @Value("${aliyun.dysms.templateCode}")
    private String templateCode;
    @Value("${aliyun.dysms.signName}")
    private String signName;
    private final RedisCache redisCache;

    public SmsServiceImpl(RedisCache redisCache) {
        this.redisCache = redisCache;
    }
    @Autowired
    private Client smsClient;

    @Override
    public void registerSmsSend(String phone) {
//       TODO 1.验证手机合法性

//        2.生成验证码
        String code=this.generateVerifyCode("MATH",4);
        UserRedisKeyPrefix keyPrefix=UserRedisKeyPrefix.USERS_REGISTER_VERIFY_CODE_STRING;
//        3.将验证码保存到redis中
        redisCache.setCacheObject(keyPrefix.fullKey(phone),code, keyPrefix.getTimeout().longValue(), keyPrefix.getUnit());
//        4.调用第三方接口，发送验证码
        try {
            this.sendSms(phone, code);
        }catch (BusinessException e){
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void sendSms(String phone, String code) throws Exception{
//         调用第三方接口，发送短信
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setPhoneNumbers(phone)
                .setTemplateParam("{\"code\":\""+code+"\"}");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse response = smsClient.sendSmsWithOptions(sendSmsRequest, runtime);
            ObjectMapper mapper = new ObjectMapper();
            String reqJson = mapper.writeValueAsString(response.body);
            log.info("[验证码] 发送短信 ====> code={},发送响应结果：{}",response.body.code,reqJson);
            if(!"ok".equalsIgnoreCase(response.body.code)){
                throw new RuntimeException(response.body.message);
            }
    }

    private String generateVerifyCode(String type, int len) {
        // 可以基于不同的type采用不同的策略生成验证码
        StringBuilder code=new StringBuilder();
        if("MATH".equalsIgnoreCase(type)){
            for(int i=0;i<len;i++){
                code.append((int)(Math.random()*10));
            }
        }else{
            String uuid= UUID.randomUUID().toString().replace("-","");
         code=new StringBuilder(uuid.substring(0,len));
        log.info("[验证码] 生成验证码 ====> type={},len={},code={}",type,len,code);
        }

        return code.toString();
    }
}
